<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">

    <title>飞鱼聊天</title>
<!--    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">-->
<!--    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>-->

<!--    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">-->
    <link rel="stylesheet" href="/css/chatmain.css" >
    <link rel="stylesheet" href="/css/external/jquery_confirm.min.css">
    <link rel="stylesheet" type="text/css" href="css/external/fontcss/bootstrap.icons.css" >
    <link rel="stylesheet" type="text/css" href="css/external/bootstrap.min.css" >

    <script src="/js/external/bootstrap.bundle.min.js"></script>

    <script src="/js/external/jquery.js"></script>
    <script src="/js/external/emoji_jQuery.min.js"></script>
    <script src="/js/external/jquery_confirm.min.js"></script>
    <script src="/js/external/main.js"></script>
    <script src="/js/external/traditional.js"></script>
    <script src="/js/external/adapter_latest.js"></script>


</head>


<body id="body-container" class="bg-light body-container">
<div id="videomain" draggable="true" class="display-none videomain videomain-border-radius no-cursor">
    <div id="videoinfo" class="videoinfo text-light videoinfo-color videoinfo-border-radius">来电</div>


    <video id="remoteVideo" class="remoteVideo" playsinline autoplay></video>

    <video id="localVideo" class="localVideo" playsinline autoplay muted></video>

    <div id="videobuttons" class="videobuttons">
        <button id="hangup" class="hangup" onclick="hangupVideoButton()">挂断</button>
        <button id="accept" class="accept" onclick="acceptVideoButton()" >接受</button>
    </div>
    <div  class="videobuttonicon videoclass">
        <button id="turnoverbutton" class="accept btn-mini" onclick="overturnvideo()" ><i class="bi bi-arrow-counterclockwise"></i></button>
        <button id="minmaxbutton" class="accept btn-mini" onclick="minmaxvideo()"><i class="bi bi-dash-square"></i></button>
    </div>
    <div  class="videobuttonicon audioclass">
        <button  class="accept btn-mini" ><i class="bi bi-ear"></i></i></button>
    </div>



</div>


<div id="imagmain" draggable="true" class="display-none  imagmain videomain-border-radius no-cursor">
    <div style="width: 100%;height: 30px;padding: 5px 5px 0 0" class="d-flex justify-content-end">
        <i onclick="closeImagPreview()" class="bi bi-x-circle"></i>
    </div>
<img id="imag-preview">



</div>

<div class="container padding-top-4" id="card-container">
    <div class="card">
        <div class="card-header  text-light d-flex justify-content-between no-cursor topbar-gradient no-border" >
            <span class="text-light no-cursor"><i class="bi bi-send"></i>&nbsp;飞鱼&nbsp;</i> </span>
            <span id="talktitle">飞鱼Chat&nbsp;</i></span>
            <span class="text-light" onclick="logout()">退出</span>
        </div>
        <div style="padding:0rem 0.75rem;background: #f5f5f5" class="card-body no-cursor">
            <div class="row" >
                <div  class="panel-container col-sm-12 col-md-4" style="background: #eae7e6;padding: 0 0;">
                    <ul class="list-group list-group-flush panel-chat-header" style="background: #eae7e6">
                        <li class="list-group-item d-flex justify-content-between no-border" style="background-image: linear-gradient(to right ,#4b8cfe , #1fd1fe)">
                            <div>
                                <div class="d-flex flex-row text-light"><img id="imaghead" class="round_icon imag-size">&nbsp;&nbsp;<div><div class="d-flex flex-column"><b>&nbsp;<span
                                        style="text-overflow:ellipsis" id="user"></span></b><span class="sign-font" id="signature"></span></div></div></div>
                            </div>
                            <div>
                                <span style="font-size: 12px"><i class="bi bi-sliders"></i></span>
                            </div>
                        </li>

                    </ul>
                    <ul class="list-group list-group-flush" style="caret-color: #4acbfe;">
                        <input id="search" type="search" class="form-control search-font-size" placeholder="搜索">
                    </ul>

                    <ul class="list-group list-group-flush list-header-font" style="background: #eae7e6">
                        <li class="d-flex justify-content-between" style="background: #f5f5f5;padding: 0 0">
                            <div id="messageList" onclick="messageListClick()" style="padding: 0.5rem 1rem" class="w-33 d-flex justify-content-center">
                                <i class="bi bi-chat"></i>&nbsp;消息</div>
                            <div id="userList" onclick="userListClick()" style="padding: 0.5rem 1rem;text-align: center;" class="w-33 d-flex justify-content-center"><i
                            class="bi bi-person-video2"></i>&nbsp;好友</div>
                            <div style="padding: 0.5rem 1rem" class="w-33 d-flex justify-content-center"><i
                                class="bi bi-people-fill" ></i>&nbsp;&nbsp;群组</div></li>

                    </ul>
                    <div class="row">
                        <div>
                            <div  class="list-group panel-chat-list" id="users" role="tablist" style="background: #eae7e6" >
                                <!--                                <a class="list-group-item   active"  data-bs-toggle="list" href="#"  >Home</a>-->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12 col-md-8 panel-chat-card"
                     id="talk-container">

                </div>
            </div>

            <div id="card-footer" class="card-footer justify-content-center">
                <div class="input-group">
                    <input id="sendmessage"  type="text" class="form-control" placeholder="请输入消息">
<!--                    <button id="plusbtn" onclick="plusClick()" class="btn btn-outline-primary btn-light"><i class="bi bi-plus-circle"></i></button>-->
                    <div class="dropup-center dropup">
                        <button class="btn btn-outline-primary btn-light dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-plus-circle"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" onclick="videoCallClick()" >视频通话</a></li>
                            <li><a class="dropdown-item" onclick="audioCallClick()" >语音通话</a></li>
                            <li><a class="dropdown-item" onclick="sendFileClick()">发送文件</a></li>
                        </ul>
                    </div>
                    <button id="emojibtn" onclick="emojiButtonClick()" class="btn btn-outline-primary btn-light"><i  class="bi bi-emoji-laughing"></i></button>
                    <button id="send"   class="btn  chat-btn-color text-light"><i class="bi bi-send"></i>&nbsp;发送</button>
                </div>
            </div>
        </div>
    </div>
    <input class="no-cursor display-none opacity-0"  type="file" id="fileupload"  multiple/>

    <script>

        var websocket;
        var lockReconnect = false;
        var reconnectCount = 0;
        var listindex = 0;
        var signList = ["我感到难过，不是因为你欺骗了我，而是因为我再也不能相信你了","一个人知道自己为什么而活，就可以忍受任何一种生活","哈库拉玛塔塔","人是苦虫，不打不行","比比，爱姆sheep","我于杀戮之中盛放，一如黎明中的花朵","死亡如风，常伴吾身","一曲肝肠断，天涯何处觅知音","无边落木萧萧下，不尽长江滚滚来","很多年之后，我有个绰号叫做西毒","睡一会罢，——便好了。","老栓慌忙摸出洋钱，抖抖的想交给他，却又不敢去接他的东西","不多不多!多乎哉?不多也。","哪里有天才，我只是把别人喝咖啡的功夫都用在了学习上"]

        var localVideo = document.getElementById('localVideo');
        var remoteVideo = document.getElementById('remoteVideo');
        var videodata = {};

        var yourConn;
        var stream;
        var RTCSessionDescription;
        var PeerConnection;
        var isVideo = false;
        var isCaller = false;
        var currentUserInfo = {};
        var isPC = true;
        var preHeadPath = "file/head/";
        var preUploadPath = "/file/upload/";
        var pictureCache = new Map();





        $(document).ready(function () {
            var url = location.href;
            var paraString = url.substring(url.indexOf("?") + 1, url.length).split("=");
            if (paraString != null && paraString.length == 2) {
                var userName = decodeURI(paraString[1])
                currentUserInfo = getCurrentUserInfo(userName);
                $("#user").html(currentUserInfo.userName);
            } else {
                $.alert({
                    title: '提示',
                    content: '没有用户！',
                });
                return
            }

            if ('WebSocket' in window) {
                websocketInit()
            } else {
                alert("not support websocket")
                return;
            }
        <!-- 默认选中消息列表 -->
            $("#messageList").addClass("text-light").addClass("list-focus")
            $("#imaghead").attr("src",preHeadPath + getUserPictureUrl(currentUserInfo.picture))
            $("#signature").html(signList[Math.floor(Math.random()*14)])

            $("#send").click(function () {

                if (currentUserInfo.to == undefined) {
                    var activeuser = $("#users > .active").val()
                    if (activeuser == undefined) {
                        // alert("当前没有其他用户在线,无法发送消息");
						commonMsg('请选中好友后再发送消息');
                        return false;
                    } else {
                        currentUserInfo.to = activeuser;
                    }

                }
                var data = {};
                data["from"] = currentUserInfo.userName;
                data["to"] = currentUserInfo.to;
                data["content"] = $("#sendmessage").val();
                data["contentType"] = "text";
                sendByMsgInfo(data)

            });

            $('#sendmessage').keydown(function (e) {
                if (e.keyCode == 13) {
                    $("#send").click()
                }
            });
            $("#card-container").click(function () {
                $(".emoji_container").hide()
            })

            $.Lemoji({
                emojiInput: '#sendmessage',
                emojiBtn: '#emojibtn',
                position: 'LEFTBOTTOM',
                length: 8,
                emojis: {
                    qq: { path: 'images/qq/', code: ':', name: 'QQ表情' },

                }
            });

            document.addEventListener('visibilitychange', function () {
                if (document.visibilityState == 'hidden') {
                    //记录页面隐藏时间
                    console.log("进入锁屏或者后台" + new Date())
                } else {
                    console.log("从锁屏或者后台唤醒" + new Date())
                    var readyState = WebSocket.readyState
                    if (readyState == 2 || readyState == 3) {
                        reconnect()
                    }
                    scrollToBottom()
                }
            });

            var cpLock = false;
            $('#search').on('compositionstart', function () {
                // 输入汉语拼音时锁住搜索框，不进行搜索，或者从汉语拼音转到字母时也可触发
                cpLock = true;
                console.log('不搜索')
                console.log($('#search').val())
            });
            $('#search').on('compositionend', function () {
                // 结束汉语拼音输入并生成汉字时，解锁搜索框，进行搜索
                cpLock = false;
                console.log('汉字搜索');
                console.log($('#search').val())
                search($('#search').val())
                // 接下去放ajax请求生成下拉框内容
            });
            $('#search').on('input', function () {
                if (!cpLock) {
                    console.log('字母搜索')
                    // 接下去放ajax请求生成下拉框内容
                    console.log($('#search').val())
                    search($('#search').val())
                }
            });



            //移动端自适应高度
            var width = $(window).width(); //获取窗口宽度
            var height = $(window).height(); //获取窗口高度

            console.log("width:"+width+" height:" + height);
            if(width < 768){
                if(height>700){
                    $("#card-footer").css('height',height*0.06+'px')
                    console.log("card-footer-height:" + '100px')
                    $("#users").css('height', height*0.29+'px')
                    console.log("")
                    $("#talk-container").css('height', height*0.45+'px')
                }else{
                    $("#card-footer").css('height',height*0.075+'px')
                    console.log("card-footer-height:" + '100px')
                    $("#users").css('height', height*0.31+'px')
                    console.log("")
                    $("#talk-container").css('height', height*0.38+'px')
                }


            }

            //可推拽

            dragable('imagmain')
            dragable('videomain')






        });

        function getCurrentUserInfo(userName){
            return  JSON.parse(window.localStorage.getItem(userName + "_data"));
        }

        isPC = function() {
            var userAgentInfo = navigator.userAgent;
            var Agents = ["Android", "iPhone","SymbianOS", "Windows Phone","iPad", "iPod"];
            var flag = true;

            for (var v = 0; v < Agents.length; v++) {
                if (userAgentInfo.indexOf(Agents[v]) > 0) {
                    flag = false;
                    break;
                }
            }

            return flag;
        }();




        function sendByMsgInfo(msginfo) {

            //通过websocket发送信息
            sendMessageByWebsocket(msginfo);
            addUserFirstMessagePrompt(msginfo,"to")
            userBubble(msginfo.to)
            //将信息append到聊天Container，并返回模板uuid
            return sendMessageTalkContainer(msginfo);


        }

        function sendMessageByWebsocket(msginfo) {
            websocket.send(JSON.stringify(msginfo));
        }

        function sendMessageTalkContainer(msginfo) {

            // var templateJSON = dialogHtmlTemplate(currentUserInfo.userName,msginfo.content,"to",msginfo.contentType)
            // $("#talk-container").append(templateJSON.message);
            // storageTalkUserMessage(msginfo["to"], templateJSON.message)
            // scrollToBottom();
            // return templateJSON.uuid;


            msginfo.position = "right"
            var templateJSON = getDialogHtmlTemplate(msginfo)
            $("#talk-container").append(templateJSON.message);
            storageCurrentTalkUserMessage(msginfo,templateJSON.uuid)
            scrollToBottom();
            $('#sendmessage').val('')
            return templateJSON.uuid;
        }




        //获取表情对应的符号
        function getEmojiStr(str) {
            var emojiList = getExecStrs(str)
            if (emojiList.length > 0) {
                for (var i = 0; i < emojiList.length; i++) {
                    var oriEmo = "[:" + emojiList[i] + "]";
                    var emo = $.emojiParse({
                        content: oriEmo,
                        emojis: [{ type: 'qq', path: 'images/qq/', code: ':' }, {
                            path: 'images/tieba/',
                            code: ';',
                            type: 'tieba'
                        }, { path: 'images/emoji/', code: ',', type: 'emoji' }]
                    });
                    str = str.replace(oriEmo, emo);
                }

            }
            return str;
        }

        //表情按钮
        function emojiButtonClick() {
            setTimeout(function () {
                window.scrollTo(0, document.body.scrollHeight)
            },400)


        }



        //格式化日期
        Date.prototype.format = function (fmt) {
            var o = {
                "M+": this.getMonth() + 1,                 //月份
                "d+": this.getDate(),                    //日
                "h+": this.getHours(),                   //小时
                "m+": this.getMinutes(),                 //分
                "s+": this.getSeconds(),                 //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds()             //毫秒
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return fmt;
        }

        function getExecStrs(str) {
            var reg = /\[\:(.*?)(?=[\]])/g;
            var list = []
            var result = null
            do {
                result = reg.exec(str)
                result && list.push(result[1])
            } while (result)
            return list
        }

        //滑动到窗口最下端
        function scrollToBottom() {
            var div = document.getElementById('talk-container');
            div.scrollTop = div.scrollHeight;
        }
        
        function dialogHtmlTemplate(messageSender,messageContent,messageType,contentType) {

            var messagevar = getEmojiStr(messageContent)
            var uuid  = getuuid();
            var filename;
            if(contentType == 'file'){
                var arr = messagevar.split('@&@')
                filename = arr[1]
                messagevar = arr[0]
            }
            var isImag = judgeFileIsImag(filename);

            var imagsrc = preUploadPath+filename;
            var fileInfo = filename + '&@&@' + uuid;
            var message = `<div><div class="d-flex ${messageType == 'to' ? 'justify-content-end dialog-head-to' : 'justify-content-start dialog-head-from'}">
                        <div class="w-30 d-flex justify-content-between border-light">
                        ${messageType == 'from' ?`<div><img class="dialog-head-icon-from" src="${ preHeadPath + pictureCache.get(messageSender) }"> </div>`:''}

                        ${contentType && contentType == 'file' && messageType == 'to' ?`<div style="padding: 0 0"><button type="button" class="dialog-button btn btn-link" onclick="openfile(${"'"+filename+"'"})">打开</button></div>`:''}
                        <div class="${messageType == 'to' ? 'dialog-content-to' : 'dialog-content-from'} "> ${isImag ? `<img onclick="clickImag(${"'" + imagsrc + "'"})" class="dialog-imag" src="${imagsrc}">` : `${messagevar}`}</div>
                        ${contentType && contentType == 'file' && messageType == 'from' ?`<div style="padding: 0 0"><button type="button" class="dialog-button btn btn-link" onclick="downloadfile(${"'" +fileInfo + "'"})">下载</button></div>`:''}
                        ${messageType == 'to' ?`<div><img class="dialog-head-icon-to" src="${ preHeadPath + pictureCache.get(messageSender) }"> </div>`:''}
                        </div>
                    </div>
                      ${contentType == 'file' ? `<div class="d-flex ${messageType == 'to' ? 'justify-content-end dialog-uploadprogress-to' : 'justify-content-start dialog-uploadprogress-from'}"><div class="w-30 d-flex" ><div class="progress" style="height: 10px;min-width: 150px">
            <div id="progressBar${uuid}" class="progress-bar progress-bar-striped progress-bar-animated" style="width: 20%"
                 role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" ></div></div><div id="showInfo${uuid}" class="${messageType == 'to' ? 'dialog-progressinfo-to' : 'dialog-progressinfo-from'}">0KB/s</div></div>
        </div>` : ''}
</div>`
            return {
                uuid,
                message
            }

        }



        function getDialogHtmlTemplate(msginfo) {

            var messagevar = getEmojiStr(msginfo.content)
            var uuid  = getuuid();
            var filename;
            if(msginfo.contentType == 'file'){
                var arr = messagevar.split('@&@')
                filename = arr[1]
                messagevar = arr[0]
            }
            var isImag = judgeFileIsImag(filename);

            var imagsrc = preUploadPath+filename;
            var fileInfo = filename + '&@&@' + uuid;
            var message = `<div ${msginfo.contentType && msginfo.contentType == 'file' ? `id='dialogdiv${uuid}'` : ''}><div class="d-flex ${msginfo.position == 'right' ? 'justify-content-end dialog-head-to' : 'justify-content-start dialog-head-from'}">
                        <div class="w-30 d-flex justify-content-between border-light">
                        ${msginfo.position == 'left' ?`<div><img class="dialog-head-icon-from" src="${ preHeadPath + pictureCache.get(msginfo.from) }"> </div>`:''}

                        ${msginfo.contentType && msginfo.contentType == 'file' && msginfo.position == 'right' ?`<div style="padding: 0 0"><button type="button" class="dialog-button dialog-button-right btn btn-link" onclick="openfile(${"'"+filename+"'"})">打开</button></div>`:''}
                        <div class="${msginfo.position == 'right' ? 'dialog-content-to' : 'dialog-content-from'} "> ${isImag ? `<img onclick="clickImag(${"'" + imagsrc + "'"})" class="dialog-imag" src="${imagsrc}">` : `${messagevar}`}</div>
                        ${msginfo.contentType && msginfo.contentType == 'file' && msginfo.position == 'left' ?`<div style="padding: 0 0"><button id="downloadbutton${uuid}" type="button" class="dialog-button dialog-button-left btn btn-link" onclick="downloadfile(${"'" +fileInfo + "'"})">${msginfo.fileState == 'downloadSuccess' ? '重新下载' : '下载'}</button></div>`:''}
                        ${msginfo.position == 'right' ?`<div><img class="dialog-head-icon-to" src="${ preHeadPath + pictureCache.get(msginfo.from) }"> </div>`:''}
                        </div>
                    </div>
                      ${msginfo.contentType == 'file' && !isImag ? `<div id="progressDiv${uuid}" class="d-flex  ${msginfo.position == 'right' ? 'justify-content-end dialog-uploadprogress-to' : 'justify-content-start dialog-uploadprogress-from'}"><div class="w-30 d-flex" ><div class="progress" style="height: 8px;min-width: 120px">
            <div id="progressBar${uuid}" class="progress-bar progress-bar-striped" ${(msginfo.fileState=='uploadSuccess' || msginfo.fileState=='downloadSuccess') ?`style="width: 100%"`:`style="width: 20%"`}
                 role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" ></div></div><div id="showInfo${uuid}" class="${msginfo.position == 'right' ? 'dialog-progressinfo-to' : 'dialog-progressinfo-from'}">${msginfo.fileStateName ? msginfo.fileStateName : '未下载'}</div></div>
        </div>` : ''}
</div>`
            return {
                uuid,
                message
            }

        }

        function judgeFileIsImag(filename) {
            if(!filename){
                return false;
            }
            let filetype = filename.substr(filename.lastIndexOf(".")+1);
            if(filetype && (filetype == "png" || filetype == "jpg" || filetype == "jpeg" || filetype == "webp" || filetype == "heic" || filetype == "svg" || filetype == "dng" || filetype == "raw" || filetype == "bmp")){
                return true;
            }else{
                return false;
            }

        }

        function clickImag(filepath) {

            $("#imagmain").show()
            divCenterShow('.imagmain')
            $("#imag-preview").attr('src',filepath)
            if(isPC){
                $("#imag-preview").css('max-width','700px')
                $("#imag-preview").css('max-height','500px')
            }else{
                $("#imag-preview").css('max-width','380px')
                $("#imag-preview").css('max-height','500px')
            }


        }

        function closeImagPreview() {

            $("#imagmain").hide()
        }


        function getuuid() {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 10; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }



            return s.join("");
        }



    </script>
    <script src="/js/websocket.js"></script>
    <script src="/js/usermsg_storagerender.js"></script>
    <script src="/js/webrtc_videochat.js"></script>
    <script src="/js/message_tips.js"></script>
    <script src="/js/drag.js"></script>
    <script src="/js/resize.js"></script>
    <script src="/js/file.js"></script>


</body>

</html>